package fm.controller;

import com.github.binarywang.wxpay.bean.WxPayOrderNotifyResponse;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import fm.config.MainConfig;
import fm.entityEnum.ClientTypeEnum;
import fm.entityEnum.ProductTypeEnum;
import fm.exception.BizException;
import fm.yichenet.service.OrderService;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 2018/1/30
 * 修改：微信订单响应接口名称修正
 * 统一订单中心名称
 * 统一查询方式
 */
@Controller
@RequestMapping("/order")
public class WxPayController extends BaseController {

    @Autowired
    MainConfig mainConfig;

    private static Logger log = LoggerFactory.getLogger(WxPayController.class);


    @Autowired
    OrderService orderService;

    @ResponseBody
    @RequestMapping(value = "/create/{clientType}/{productType}",method = RequestMethod.POST)
    public Map wechatOrderCreate(@RequestParam String orderIds,
                                 @PathVariable ClientTypeEnum clientType,
                                 @PathVariable ProductTypeEnum productType,
                                 HttpServletRequest request) throws Exception {
        Map res = new HashedMap();
        try {
            Object result = orderService.prePayOrder(orderIds, clientType, productType, request);
            if (result != null) {
                res.put("data", result);
            } else {
                throw new BizException("下单失败!");
            }
            this.success(res);
        } catch (BizException e) {
            log.error("支付失败", e);
            this.failed(res, e.getMessage());
        } catch (WxErrorException e) {
            log.error("微信支付失败！:", e);
            this.failed(res, "微信支付发生错误：" + e.getMessage());
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/notify/{clientType}/{productType}",method = RequestMethod.POST)
    public String wechatPayNotify(@PathVariable ClientTypeEnum clientType,
                                  @PathVariable ProductTypeEnum productType,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {

        try {
            return orderService.notifyOrder(clientType, productType, request, response);
        } catch (BizException ex) {
            log.info("wxpay/payresult info BizException msg : {} ", ex);
            return WxPayOrderNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e);
            return WxPayOrderNotifyResponse.fail(e.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping(value = "/result/{clientType}/{productType}",method = RequestMethod.POST)
    public Map queryReuslt(@PathVariable ClientTypeEnum clientType,
                           @RequestParam String orderIds,
                           @PathVariable ProductTypeEnum productType) {
        Map res = new HashMap();
        try {

            WxPayOrderQueryResult wxPayOrderQueryResult = orderService.getOrderPayResult(orderIds, productType, clientType);

            res.put("data", wxPayOrderQueryResult);
            this.success(res);
        } catch (BizException ex) {
            log.info("occur biz error : {} ", ex);
            this.failed(res, ex);
        } catch (Exception e) {
            log.error("occur error", e);
            this.failed(res, "操作失败，请重试或者联系管理员解决!");
        }

        return res;
    }

}
